import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useProjectStore = defineStore('project', () => {
  // 项目基本信息
  const project = ref({
    id: null,
    name: '未命名项目',
    description: '',
    version: '1.0.0',
    createdAt: null,
    updatedAt: null,
    thumbnail: null,
    tags: [],
    category: 'residential', // residential, commercial, industrial
    status: 'draft' // draft, in_progress, completed, archived
  })

  // 项目设置
  const settings = ref({
    canvasWidth: 800,
    canvasHeight: 600,
    unit: 'cm', // cm, m, mm, inch
    scale: 1,
    backgroundColor: '#ffffff',
    gridColor: '#e5e7eb',
    snapToGrid: true,
    snapToObjects: true,
    showDimensions: true,
    showLabels: true,
    showGrid: true
  })

  // 项目统计
  const statistics = ref({
    totalElements: 0,
    totalLayers: 0,
    totalGroups: 0,
    fileSize: 0,
    lastModified: null
  })

  // 计算属性
  const projectName = computed(() => project.value.name)
  const isNewProject = computed(() => !project.value.id)
  const canSave = computed(() => project.value.name.trim().length > 0)
  const projectSize = computed(() => {
    const size = statistics.value.fileSize
    if (size < 1024) return `${size}B`
    if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)}KB`
    return `${(size / (1024 * 1024)).toFixed(1)}MB`
  })

  // Actions
  const createProject = (projectData = {}) => {
    const now = new Date().toISOString()
    project.value = {
      id: null,
      name: '未命名项目',
      description: '',
      version: '1.0.0',
      createdAt: now,
      updatedAt: now,
      thumbnail: null,
      tags: [],
      category: 'residential',
      status: 'draft',
      ...projectData
    }
  }

  const loadProject = async (projectId) => {
    try {
      // 从API或本地存储加载项目
      const projectData = await fetchProject(projectId)
      project.value = { ...project.value, ...projectData }
      updateStatistics()
    } catch (error) {
      throw new Error(`加载项目失败: ${error.message}`)
    }
  }

  const saveProject = async () => {
    try {
      const now = new Date().toISOString()
      project.value.updatedAt = now
      
      if (project.value.id) {
        // 更新现有项目
        await updateProject(project.value)
      } else {
        // 创建新项目
        const savedProject = await createProjectAPI(project.value)
        project.value.id = savedProject.id
      }
      
      updateStatistics()
    } catch (error) {
      throw new Error(`保存项目失败: ${error.message}`)
    }
  }

  const exportProject = async (format = 'json') => {
    try {
      // 导出项目数据
      const exportData = {
        project: project.value,
        settings: settings.value,
        statistics: statistics.value,
        // 这里还需要包含设计数据
      }
      
      return exportData
    } catch (error) {
      throw new Error(`导出项目失败: ${error.message}`)
    }
  }

  const importProject = async (projectData) => {
    try {
      // 验证项目数据格式
      if (!projectData.project || !projectData.settings) {
        throw new Error('无效的项目数据格式')
      }
      
      project.value = { ...project.value, ...projectData.project }
      settings.value = { ...settings.value, ...projectData.settings }
      
      updateStatistics()
    } catch (error) {
      throw new Error(`导入项目失败: ${error.message}`)
    }
  }

  const updateProjectInfo = (updates) => {
    project.value = { ...project.value, ...updates }
  }

  const updateSettings = (newSettings) => {
    settings.value = { ...settings.value, ...newSettings }
  }

  const updateStatistics = () => {
    // 更新项目统计信息
    statistics.value = {
      totalElements: 0, // 从设计数据计算
      totalLayers: 0,   // 从图层数据计算
      totalGroups: 0,   // 从组数据计算
      fileSize: 0,      // 计算文件大小
      lastModified: new Date().toISOString()
    }
  }

  const generateThumbnail = async () => {
    try {
      // 生成项目缩略图
      // 这里需要调用Canvas API生成缩略图
      const thumbnail = await captureCanvas()
      project.value.thumbnail = thumbnail
    } catch (error) {
      console.error('生成缩略图失败:', error)
    }
  }

  const reset = () => {
    createProject()
    settings.value = {
      canvasWidth: 800,
      canvasHeight: 600,
      unit: 'cm',
      scale: 1,
      backgroundColor: '#ffffff',
      gridColor: '#e5e7eb',
      snapToGrid: true,
      snapToObjects: true,
      showDimensions: true,
      showLabels: true
    }
    statistics.value = {
      totalElements: 0,
      totalLayers: 0,
      totalGroups: 0,
      fileSize: 0,
      lastModified: null
    }
  }

  // 模拟API调用
  const fetchProject = async (id) => {
    // 模拟API调用
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          id,
          name: '示例项目',
          description: '这是一个示例项目',
          version: '1.0.0',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        })
      }, 1000)
    })
  }

  const createProjectAPI = async (projectData) => {
    // 模拟API调用
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          id: Date.now().toString(),
          ...projectData
        })
      }, 1000)
    })
  }

  const updateProject = async (projectData) => {
    // 模拟API调用
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(projectData)
      }, 1000)
    })
  }

  const captureCanvas = async () => {
    // 模拟Canvas截图
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve('')
      }, 500)
    })
  }

  return {
    // 状态
    project,
    settings,
    statistics,
    
    // 计算属性
    projectName,
    isNewProject,
    canSave,
    projectSize,
    
    // Actions
    createProject,
    loadProject,
    saveProject,
    exportProject,
    importProject,
    updateProjectInfo,
    updateSettings,
    updateStatistics,
    generateThumbnail,
    reset
  }
})
